package com.kgc.ssm.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kgc.ssm.beans.Goods;
import com.kgc.ssm.beans.Items;
import com.kgc.ssm.beans.User;
import com.kgc.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import com.kgc.ssm.service.GoodsService;
import com.kgc.ssm.service.ItemsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.servlet.http.HttpSession;
import java.util.Map;


import org.springframework.web.bind.annotation.RequestParam;
import sun.misc.BASE64Encoder;


/**
 * @author Administrator
 * @version 1.0
 * @date 2021/11/24 9:53
 * @Description:控制类
 */
@Controller
public class WebController {

    @Autowired
    private UserService userService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ItemsService itemsService;


    /**
     * 注册成功或失败 返回页面
     * @param user
     * @param
     * @return
     * @throws IOException
     */
    @RequestMapping("registerUseraction")
    public String webActionRegisterUser(User user) throws IOException {

        MessageDigest md5 = null;

        try {
            md5 = MessageDigest.getInstance("MD5");

        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();
        }
        BASE64Encoder base64 = new BASE64Encoder();

        if (userService.selectOneUser(user.getUid()) == 0 && user.getPwd()!= null ){

            if (user.getUid().length()<11 && user.getUid().length()>2){

                if (user.getPwd().length()<15 && user.getPwd().length()>5){

                    String newpwd = base64.encode(md5.digest(user.getPwd().getBytes(StandardCharsets.UTF_8)));

                    user.setPwd(newpwd);

                        userService.insertUser(user);

                    return "index";
                }
            }
        }
        return "login";
    }

    /**
     *
     * @param request
     * @param response
     * @throws IOException  用户名局部刷新内容
     */
    @RequestMapping("userregisteruid")
    @ResponseBody
    public void webUidRegisterUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("uid");
        response.setCharacterEncoding("utf-8");
        if (userService.selectOneUser(username) == 0 ){
            if (username.length()<11 && username.length()>2){
                response.getWriter().println("(用户名可以使用)");
                System.out.println("用户名可以使用");
            }else{
                response.getWriter().println("(用户名不可用，请输入3-10长度的用户名)");
                System.out.println("用户名不可用");
            }
        }else {
            response.getWriter().println("(用户名已被注册或不可用，请输入3-10长度的用户名)");
            System.out.println("用户名不可用");
        }
    }

    /**
     * 根据用户名和密码查询用户信息返回成功 登陆成功
     */
    @RequestMapping("webDLUser")
    public String webDlUser(@RequestParam String uid,String pwd,
                            HttpServletRequest request,HttpServletResponse response) throws IOException {

        HttpSession session = request.getSession(true);

        session.setAttribute("name",uid);

        session.setAttribute("pass",pwd);

        MessageDigest md5 = null;

        try {

            md5 = MessageDigest.getInstance("MD5");

        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();
        }
        BASE64Encoder base64 = new BASE64Encoder();

        String newpwd = base64.encode(md5.digest(pwd.getBytes(StandardCharsets.UTF_8)));

        if (userService.selectAssignedUser(uid, newpwd) == 0){
            response.getWriter().println("您输入的用户名或密码不可用请重新输入");
            return "forward:login.jsp";
        }
        return "redirect:index.jsp";
    }

//    /**
//     *
//     * @param request
//     * @param response
//     * @throws IOException  密码局部刷新内容
//     */
//    @RequestMapping("userregisterpass")
//    @ResponseBody
//    public void webPassRegisterUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        String pass = request.getParameter("pwd");
//        response.setCharacterEncoding("utf-8");
//        if (pass.length()<15 && pass.length()>6){
//            response.getWriter().println("密码符合要求 可以使用");
//            System.out.println("密码可以使用");
//        } else {
//            response.getWriter().println("包含非法字符或长度不符合要求，请输入6-15长度的密码");
//            System.out.println("密码不可用");
//        }
//    }

    /**
     *
     * @param username
     * @param password
     * @param map
     * @return 后台管理员登录
     */
    @RequestMapping("/After_end/AfterLogin")
    public String afterLogin(@RequestParam String username, String password, Map<String,Object> map){
        Boolean flag = userService.afterLogin(username,password);
        if (flag){
            return "redirect:index.jsp";
        }else{
            map.put("message", "用户名或者密码错误！");
            return "forward:login.jsp";
        }

    }


    /**
     * @Author bai
     * @Date  2021/11/24
     *Description:查询所有商品详情列表
     */
    @RequestMapping("/After_end/AfterGoodList")
    public String afterGoodsList(@RequestParam(defaultValue = "1") Integer page,Map<String,Object> map, HttpServletRequest request){
        PageHelper.startPage(page,10);
        List<Goods> goodsList = goodsService.queryGoodsList();
        PageInfo<Goods> pg = new PageInfo<>(goodsList);
        map.put("page",pg);
        map.put("categorys",itemsService.queryItemsList());
        return "After_end/GoodList";
    }
//    @RequestMapping("/After_end/AfterGoodList")
//    public String afterGoodsList(Map<String,Object> map, HttpServletRequest request){
//        Integer pid = request.getParameter("pid") == null ? 0 : Integer.valueOf(request.getParameter("pid"));
//        map.put("adoc",goodsService.queryGoodsList(pid));
//        map.put("categorys",itemsService.queryItemsList());
//        return "After_end/GoodList";
//    }

    /**
     * @Author bai
     * @Date  2021/11/24
     *Description:删除商品
     */
    @RequestMapping("/After_end/delAfterGoods")
    public String afterDelGoods(Integer pid){
        goodsService.delAfterGoods(pid);
        return "redirect:AfterGoodList";
    }

    /**
     * @MethodName
     * @Description  商品展示查询
     * @Author lqh
     * @Version V1.0.0
     * @Since 2021/11/24
     */

    @RequestMapping("/selectAll")
    public  String webGoodsList( @RequestParam(defaultValue="1") Integer currentPage,
                                 @RequestParam(defaultValue ="1") Integer sort,
                                 HttpServletRequest request,
                                 Map<String,Object> map){
        //插件实现 获取当前页  限制pageSize长度
        PageHelper.startPage(currentPage,24);
        List<Goods> list = null;
        switch (sort){
            case 1:
                list= goodsService.selectAll();
                map.put("status",1);
                break;
            case 2:
                list= goodsService.selectAllByPriceFirst();
                map.put("status",2);
                break;
            case 3:
                list= goodsService.selectAllByPriceSecond();
                map.put("status",3);
                break;
            case 4:
                list= goodsService.selectAllByStock();
                map.put("status",4);
                break;
            default:
                break;
        }
        PageInfo<Goods> pageInfo=new PageInfo<>(list);
        map.put("pageinfo",pageInfo);
        return "shop";
    }



    /**
     * @Author bai
     * @Date  2021/11/25
     *Description:后台管理商品列表模糊查询
     */
    @RequestMapping("/After_end/DimGoodsItems")
    public String AfterGoodsItemsDim(@RequestParam(defaultValue = "1") Integer page, String keyword, Map<String,Object> map){
        PageHelper.startPage(page,10);
        List<Goods> goodsList = goodsService.AfterDimGoodsItems(keyword);
        PageInfo<Goods> pg = new PageInfo<>(goodsList);
        map.put("page",pg);
        return "After_end/GoodList";
    }

    /**
     * @Author bai
     * @Date  2021/11/25
     *Description:跳转后台管理商品修改页面
     */
    @RequestMapping("/After_end/toAfterMod")
    public String toAfterModGoods(Map<String,Object> map,@RequestParam Integer pid){
        Goods goods = goodsService.AfterSelectGoods(pid);
        map.put("good",goods);
        List<Items> items = itemsService.queryItemsList();
        map.put("items",items);
        return "After_end/ModGood";
    }

    /**
     * @Author bai
     * @Date  2021/11/25
     *Description:修改后台管理系统商品
     */
    @RequestMapping("/After_end/AfterModGoods")
    public String AfterModGoods(Goods goods){
        goodsService.AfterModGoods(goods);
        return "redirect:AfterGoodList";
    }

    /**
     * @Author bai
     * @Date  2021/11/25
     *Description:跳转后台管理的商品新增页
     */
    @RequestMapping("/After_end/toAfterAddGoods")
    public String AfterAddGoods(Map<String,Object> map){
        map.put("items",itemsService.queryItemsList());
        return "After_end/addGood";
    }

    /**
     * @Author bai
     * @Date  2021/11/25
     *Description:新增后台管理商品
     */
    @RequestMapping("/After_end/AfterAddGoods")
    public String AfterAddGoods(Goods goods){
        Long time = new Date().getTime();
        goods.setPid(Integer.valueOf(time.toString().substring(4,13)));
        goodsService.AfterAddGoods(goods);
        return "redirect:AfterGoodList";
    }



}
